import { JSEncrypt } from "jsencrypt";
import cookies from "vue-cookies";
export function getUrlParams(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]).replace("/", "");
  }
  return null;
}

export function encryptFn(value, key) {
  let encrypt = new JSEncrypt({ default_key_size: 2048 });
  encrypt.setPublicKey(key);
  return encrypt.encrypt(value);
}

export function decrypt(value, key) {
  let jsEncrypt = new JsEncrypt({ default_key_size: 2048 });
  jsEncrypt.setPrivateKey(key); // 设置私钥
  return jsEncrypt.decrypt(value);
}

/**
 * 将时间戳转换为日期格式
 * @param {string} time
 */
export function transformTimestamp(time) {
  let date = new Date(time);
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? "0" + m : m;
  let d = date.getDate();
  d = d < 10 ? "0" + d : d;
  let h = date.getHours();
  h = h < 10 ? "0" + h : h;
  let minute = date.getMinutes();
  minute = minute < 10 ? "0" + minute : minute;
  let sec = date.getSeconds();
  sec = sec < 10 ? "0" + sec : sec;
  return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + sec;
}

export function delParam(paramKey) {
  var url = window.location.href; // 页面url
  var urlParam = window.location.search.substr(1); // 页面参数
  var beforeUrl = url.substr(0, url.indexOf("?")); // 页面主地址（参数之前地址）
  var nextUrl = "";

  var arr = [];
  if (urlParam !== "") {
    var urlParamArr = urlParam.split("&"); // 将参数按照&符分成数组
    for (var i = 0; i < urlParamArr.length; i++) {
      var paramArr = urlParamArr[i].split("="); // 将参数键，值拆开
      // 如果键与要删除的不一致，则加入到参数中
      if (paramArr[0] !== paramKey) {
        arr.push(urlParamArr[i]);
      }
    }
  }
  if (arr.length > 0) {
    nextUrl = "?" + arr.join("&");
  }
  url = beforeUrl + nextUrl;
  return url;
}

export default {
  // 获取连接参数值
  getUrlParams(name) {
    return getUrlParams(name);
  },
  delParam(name) {
    return delParam(name);
  },
  // 判断安卓或者ios终端
  testMobileType() {
    const u = navigator.userAgent;
    const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; // android终端
    const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
    if (isAndroid) {
      return "android";
    } else if (isiOS) {
      return "ios";
    } else {
      return "pc";
    }
  },
  // 校验手机号码
  isPhone(val) {
    var patrn = /^(((1[3456789][0-9]{1})|(15[0-9]{1}))+\d{8})$/;
    if (!patrn.test(val) || val === "") {
      return false;
    } else {
      return true;
    }
  },
  // 检验车牌号
  isCarNum(val) {
    var patrn = /^(?:[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领 A-Z]{1}[A-HJ-NP-Z0-9]{1}(?:(?:[0-9]{5}[DF])|(?:[DF](?:[A-HJ-NP-Z0-9])[0-9]{4})))|(?:[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领 A-Z]{1}[A-Z0-9]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9 挂学警港澳使领]{1})$/;
    if (!patrn.test(val)) {
      return false;
    } else {
      return true;
    }
  },
  // 校验车架号
  isVehicle(val) {
    var patrn = /^[A-HJ-NP-Za-hj-np-z0-9]+$/;
    if (!patrn.test(val) || val === "") {
      return false;
    } else {
      return true;
    }
  },
  // 判断输入框是否有表情
  isEmojiCharacter(substring) {
    for (var i = 0; i < substring.length; i++) {
      const hs = substring.charCodeAt(i);
      if (hs >= 0xd800 && hs <= 0xdbff) {
        if (substring.length > 1) {
          const ls = substring.charCodeAt(i + 1);
          var uc = (hs - 0xd800) * 0x400 + (ls - 0xdc00) + 0x10000;
          if (uc >= 0x1d000 && uc <= 0x1f77f) {
            return true;
          }
        }
      } else if (substring.length > 1) {
        const ls = substring.charCodeAt(i + 1);
        if (ls === 0x20e3) {
          return true;
        }
      } else {
        if (hs >= 0x2100 && hs <= 0x27ff) {
          return true;
        } else if (hs >= 0x2b05 && hs <= 0x2b07) {
          return true;
        } else if (hs >= 0x2934 && hs <= 0x2935) {
          return true;
        } else if (hs >= 0x3297 && hs <= 0x3299) {
          return true;
        } else if (
          hs === 0xa9 ||
          hs === 0xae ||
          hs === 0x303d ||
          hs === 0x3030 ||
          hs === 0x2b55 ||
          hs === 0x2b1c ||
          hs === 0x2b1b ||
          hs === 0x2b50
        ) {
          return true;
        }
      }
    }
  },
  // 日期格式化
  dateFormat(date, fmt) {
    var o = {
      "M+": date.getMonth() + 1,
      "d+": date.getDate(),
      "h+": date.getHours(),
      "m+": date.getMinutes(),
      "s+": date.getSeconds(),
      "q+": Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds()
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
    }
    return fmt;
  },
  // 时间格式化
  TimeFormat(val, s) {
    if (!val) {
      return "";
    }
    if (s) {
      val = val * 1000;
    }
    var date = new Date(val);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var min = date.getMinutes();
    var second = date.getSeconds();
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    hour = hour < 10 ? "0" + hour : hour;
    min = min < 10 ? "0" + min : min;
    second = second < 10 ? "0" + second : second;
    return year + "." + month + "." + day;
  },
  // 日期年月日
  getDate() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    return year + "-" + month + "-" + day;
  },

  transformTime(time, type) {
    let date =
      time.slice(0, 4) + "-" + time.slice(4, 6) + "-" + time.slice(6, 8);
    let dateTime =
      time.slice(8, 10) + ":" + time.slice(10, 12) + ":" + time.slice(12);

    if (type === "date") {
      return date;
    } else {
      return date + " " + dateTime;
    }
  },
  // 压缩图片
  dealImage(path, obj, callback) {
    var img = new Image();
    img.src = path;
    img.onload = function() {
      var that = this;
      // 默认按比例压缩
      var w = that.width;
      var h = that.height;
      var scale = w / h;
      w = obj.width || w;
      h = obj.height || w / scale;
      var quality = 0.5; // 默认图片质量为0.7
      // 生成canvas
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      // 创建属性节点
      var anw = document.createAttribute("width");
      anw.nodeValue = w;
      var anh = document.createAttribute("height");
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w, h);
      // 图像质量
      if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
        quality = obj.quality;
      }
      // quality值越小，所绘制出的图像越模糊
      var base64 = canvas.toDataURL("image/jpeg", quality);
      // 回调函数返回base64的值
      callback(base64);
    };
  },
  // 图片转成base64
  getImgData(img, dir, next) {
    var image = new Image();
    image.onload = function() {
      var degree = 0;
      var drawWidth;
      var drawHeight;
      var width;
      var height;
      drawWidth = this.naturalWidth;
      drawHeight = this.naturalHeight;
      // 以下改变一下图片大小
      var canvas = document.createElement("canvas");
      canvas.width = width = drawWidth;
      canvas.height = height = drawHeight;
      var context = canvas.getContext("2d");
      // 判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
      switch (dir) {
        // iphone横屏拍摄，此时home键在左侧
        case 3:
          degree = 180;
          drawWidth = -width;
          drawHeight = -height;
          break;
        // iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
        case 6:
          canvas.width = height;
          canvas.height = width;
          degree = 90;
          drawWidth = width;
          drawHeight = -height;
          break;
        // iphone竖屏拍摄，此时home键在上方
        case 8:
          canvas.width = height;
          canvas.height = width;
          degree = 270;
          drawWidth = -width;
          drawHeight = height;
          break;
      }
      // 使用canvas旋转校正
      context.rotate((degree * Math.PI) / 180);
      context.drawImage(this, 0, 0, drawWidth, drawHeight);
      // 返回校正图片
      next(canvas.toDataURL("image/jpeg", 0.8));
    };
    image.src = img;
  },
  // 防抖
  _debounce(fn, delay) {
    var delay1 = delay || 200;
    var timer;
    return function() {
      var th = this;
      var args = arguments;
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(function() {
        timer = null;
        fn.apply(th, args);
      }, delay1);
    };
  },
  // 节流
  _throttle(fn, interval) {
    var last;
    var timer;
    var interval1 = interval || 200;
    return function() {
      var th = this;
      var args = arguments;
      var now = +new Date();
      if (last && now - last < interval) {
        clearTimeout(timer);
        timer = setTimeout(function() {
          last = now;
          fn.apply(th, args);
        }, interval1);
      } else {
        last = now;
        fn.apply(th, args);
      }
    };
  },
  // 设置cookie
  setCookie(cname, cvalue, exdays) {
    cookies.set(cname, cvalue, exdays * 24 * 60 * 60 * 1000);
  },
  // 获取cookie
  getCookie: function(cname) {
    return cookies.get(cname);
  },
  // 清除cookie
  clearCookie: function() {
    cookies.remove("UID");
  },
  intervalTime: function(startTime, endTime) {
    const dateBegin = new Date(startTime.replace(/-/g, "/")); // 将-转化为/，使用new Date
    const dateEnd = new Date(endTime.replace(/-/g, "/"));
    const dateDiff = dateEnd.getTime() - dateBegin.getTime(); // 时间差的毫秒数
    const dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); // 计算出相差天数
    const leave1 = dateDiff % (24 * 3600 * 1000); // 计算天数后剩余的毫秒数
    const hours = Math.floor(leave1 / (3600 * 1000)); // 计算出小时数
    // 计算相差分钟数
    const leave2 = leave1 % (3600 * 1000); // 计算小时数后剩余的毫秒数
    const minutes = Math.floor(leave2 / (60 * 1000)); // 计算相差分钟数
    // 计算相差秒数
    const leave3 = leave2 % (60 * 1000); // 计算分钟数后剩余的毫秒数
    const seconds = Math.round(leave3 / 1000);
    return (
      (dayDiff ? dayDiff + "天" : "") +
      (hours ? hours + "小时" : "") +
      (minutes ? minutes + "分" : "") +
      (seconds ? seconds + "秒" : "")
    );
  },
  validateImage: async function(pathImg) {
    var ImgObj = new Image();
    ImgObj.src = pathImg;
    ImgObj.onload = await function() {
      if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
        return true;
      } else {
        return false;
      }
    };
  },
  judgeBigScreen: function() {
    let result = false;
    const rate = window.screen.height / window.screen.width;
    const limit =
      window.screen.height === window.screen.availHeight ? 1.8 : 1.65; // 临界判断值

    // window.screen.height为屏幕高度
    //  window.screen.availHeight 为浏览器 可用高度
    // 返回true的话 则为全面屏
    if (rate > limit) {
      result = true;
    }
    return result;
  },
  objectToParamString: function(paramObj) {
    // object转为url参数（？后面的参数）
    if (!paramObj) {
      return "";
    }
    const paramList = [];
    Object.keys(paramObj) &&
      Object.keys(paramObj).forEach(key => {
        const val = paramObj[key];
        if (val.constructor === Array) {
          val.forEach(_val => {
            paramList.push(key + "=" + _val);
          });
        } else {
          paramList.push(key + "=" + val);
        }
      });
    return paramList.join("&");
  },
  formatTimeString: function(time) {
    time = time / 1000;
    const DAY_NUMBER = 24 * 60 * 60;
    const HOURS_NUMBER = 60 * 60;
    const MINUTES_NUMBER = 60;

    time = Number(time);
    // 天数
    const day = Math.floor(time / DAY_NUMBER);
    // 小时数
    const hours = Math.floor((time - day * DAY_NUMBER) / HOURS_NUMBER);
    // 分钟数
    const minutes = Math.floor(
      (time - day * DAY_NUMBER - hours * HOURS_NUMBER) / MINUTES_NUMBER
    );
    // 秒数
    const seconds = Math.floor(
      time - day * DAY_NUMBER - hours * HOURS_NUMBER - minutes * MINUTES_NUMBER
    );

    let timeStr = "";
    if (day > 0) {
      timeStr += day + "天";
    }
    if (hours > 0) {
      timeStr += hours + "小时";
    }
    if (minutes > 0) {
      timeStr += minutes + "分";
    }
    timeStr += seconds + "秒";

    return timeStr;
  }
};
